package com.log4jviewer.ui.preferences.filters;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;

import com.log4jviewer.filters.FilterConstants;
import com.log4jviewer.filters.FilterItemModel;
import com.log4jviewer.filters.FilterItemModel.LogicOperand;

/**
 * Create possibility modify the Logic cell in Rules Table
 * 
 * @author <a href="mailto:solid.danil@gmail.com">Daniil Lopatin</a>
 */
public class RulesLogicCellEditor extends EditingSupport {

    private final TableViewer tableViewer;

    public RulesLogicCellEditor(final TableViewer tableViewer) {
        super(tableViewer);
        this.tableViewer = tableViewer;
    }

    @Override
    protected CellEditor getCellEditor(final Object element) {
        return new ComboBoxCellEditor(tableViewer.getTable(), FilterConstants.LOGIC_OPERANDS, SWT.READ_ONLY);
    }

    @Override
    protected boolean canEdit(final Object element) {
        boolean canEdit = true;

        if (tableViewer.getTable().getSelectionIndex() == 0) {
            canEdit = false;
        }
        return canEdit;
    }

    @Override
    protected Object getValue(final Object element) {
        FilterItemModel filterItemModel = (FilterItemModel) element;
        int logicOperandIndex = 0;

        for (int i = 0; i < FilterConstants.LOGIC_OPERANDS.length; i++) {
            if (filterItemModel.getLogicOperand().equals(FilterConstants.LOGIC_OPERANDS[i])) {
                logicOperandIndex = i;
                break;
            }
        }
        return logicOperandIndex;
    }

    @Override
    protected void setValue(final Object element, final Object value) {
        FilterItemModel item = (FilterItemModel) element;
        LogicOperand[] logicOperands = FilterItemModel.LogicOperand.values();
        item.setLogicOperand(logicOperands[(Integer) value]);
        tableViewer.update(item, null);
    }
}
